// pages/venue/detail.js
const api = require('../../utils/api');

Page({
  data: {
    venueId: null,
    venueInfo: null,
    showFacilities: false,
    showOpeningHours: false,
    timeSlots: [],
    selectedDate: '',
    today: '',
    dateList: [],
    loading: true
  },

  onLoad: function(options) {
    // 获取场馆ID
    if (options.id) {
      this.setData({
        venueId: options.id
      });
      
      // 缓存当前场馆ID
      wx.setStorageSync('venue_id', options.id);
      
      // 加载场馆详情
      this.loadVenueDetail();
      
      // 准备日期选择器数据
      this.prepareDatePicker();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 准备日期选择器数据
  prepareDatePicker: function() {
    const today = new Date();
    const dateList = [];
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    
    // 生成未来7天的日期
    for (let i = 0; i < 7; i++) {
      const date = new Date(today);
      date.setDate(today.getDate() + i);
      
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      
      const weekday = weekdays[date.getDay()];
      const label = i === 0 ? '今天' : weekday;
      
      dateList.push({
        date: `${year}-${month}-${day}`,
        day: day,
        label: label
      });
    }
    
    this.setData({
      dateList: dateList,
      selectedDate: dateList[0].date,
      today: dateList[0].date
    });
    
    // 加载当日时间段
    this.loadTimeSlots(dateList[0].date);
  },
  
  // 加载场馆详情
  loadVenueDetail: function() {
    wx.showLoading({
      title: '加载中...',
    });
    
    api.venue.getVenueDetail(this.data.venueId)
      .then(res => {
        if (res && res.success && res.data) {
          const venueInfo = res.data;
          
          this.setData({
            venueInfo: venueInfo,
            loading: false
          });
        } else {
          wx.showToast({
            title: '获取场馆信息失败',
            icon: 'none'
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      })
      .catch(err => {
        console.error('获取场馆详情失败:', err);
        wx.showToast({
          title: '获取场馆详情失败',
          icon: 'none'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      })
      .finally(() => {
        wx.hideLoading();
      });
  },
  
  // 加载指定日期的时间段
  loadTimeSlots: function(date) {
    wx.showLoading({
      title: '加载时间段...',
    });
    
    api.venue.getVenueTimeSlots(this.data.venueId, date)
      .then(res => {
        if (res && res.success && res.data) {
          this.setData({
            timeSlots: res.data
          });
        } else {
          console.log('获取时间段失败：', res);
          // 设置为空数组
          this.setData({
            timeSlots: []
          });
        }
      })
      .catch(err => {
        console.error('获取时间段失败:', err);
        // 设置为空数组
        this.setData({
          timeSlots: []
        });
      })
      .finally(() => {
        wx.hideLoading();
      });
  },
  
  // 选择日期
  onSelectDate: function(e) {
    const date = e.currentTarget.dataset.date;
    this.setData({
      selectedDate: date
    });
    
    // 加载所选日期的时间段
    this.loadTimeSlots(date);
  },
  
  // 切换设施信息显示状态
  toggleFacilities: function() {
    this.setData({
      showFacilities: !this.data.showFacilities
    });
  },
  
  // 切换营业时间显示状态
  toggleOpeningHours: function() {
    this.setData({
      showOpeningHours: !this.data.showOpeningHours
    });
  },
  
  // 返回上一页
  onTapBack: function() {
    wx.navigateBack();
  },
  
  // 查看地图
  onTapViewMap: function() {
    wx.navigateTo({
      url: `/pages/venue/map?id=${this.data.venueId}`
    });
  },
  
  // 查看时间段详情
  onTapTimeSlot: function(e) {
    const slotIndex = e.currentTarget.dataset.index;
    const timeSlot = this.data.timeSlots[slotIndex];
    
    // 这里可以添加查看时间段详情的逻辑
    // 例如跳转到预约页面等
    
    // 临时显示提示
    wx.showToast({
      title: `选择了 ${timeSlot.start_time} - ${timeSlot.end_time}`,
      icon: 'none'
    });
  },
  
  // 前往预约
  onTapBook: function() {
    wx.navigateTo({
      url: `/pages/venue/room?venueId=${this.data.venueId}`
    });
  }
})